package com.opesoft.fw.mvc.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.opesoft.fw.core.Constants;
import com.opesoft.fw.mvc.Action;
import com.opesoft.fw.mvc.Token;

public abstract class StandardAction implements Action
{
	public HttpServletRequest request;
	public HttpServletResponse response;
	public HttpSession session;
	public Logger log=Logger.getLogger(this.getClass());
	public boolean token=true;

	public void init(HttpServletRequest request,HttpServletResponse response)
	{
		this.request=request;
		this.response=response;
		this.session=request.getSession();

		// 检查令牌是否有效
		Object tokenValue=request.getParameter(Constants.MVC_TOKEN);
		if(tokenValue!=null)
		{
			Token token=(Token)session.getAttribute(Constants.MVC_SESSION_TOKENS);
			if(token!=null) this.token=token.verify(tokenValue.toString());
			else this.token=false;
		}
	}

	public void before()
	{

	}

	public void after()
	{

	}

	public Object extractForm(Object bean)
	{
		try
		{
			if(bean!=null&&this.request!=null) BeanUtils.populate(bean,this.request.getParameterMap());
		}
		catch(Exception e)
		{
			log.error(e);
			if(Constants.MODE.equalsIgnoreCase("develop")) e.printStackTrace();
		}
		return bean;
	}

	public Object extractForm(Class clazz)
	{
		try
		{
			return this.extractForm(clazz.newInstance());
		}
		catch(InstantiationException e)
		{
			e.printStackTrace();
		}
		catch(IllegalAccessException e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
